Strict
Import brl.filesystem
Import "bluecc_head.bmx"

Global look, token:String
Global vline = 1
Global error_count


Function echo(s:String)
	WriteStdout s
EndFunction

Function echoln(s:String)
	WriteStdout s+"~n"
EndFunction

Function low(x:Byte)
	If x >= 65 And x <= 90 Then x:+32
	Return x
EndFunction

Function error(s:String, f = False, l = -1)
	If l = -1 Then l = vline
	WriteStderr "~n["+l+"] error: "+s+"~n"
	error_count :+ 1
	If f Then WriteStderr "Compilation aborted.";End
EndFunction

Function isalpha(x:Byte)
	Return (x >= 65 And x <= 90) Or (x >= 97 And x <= 122)
EndFunction

Function isdigit(x:Byte)
	Return x >= 48 And x <= 57
EndFunction

Function isalnum(x:Byte)
	Return isalpha(look) Or isdigit(look)
EndFunction

Function read_repos(x)
	filestream.seek filestream.pos()-x-1
	GetChar
EndFunction

Function GetChar()
	If filestream.Eof() Then look = 0;Return
	look = filestream.ReadByte()
	If look = 10 Then vline:+1
EndFunction

Function match(x:String)
	If look <> Asc x Then error "expected "+x, True
	GetChar
	skipblanks
EndFunction

Function skipwhite()
	While look = 9 Or look = 32 Or look = 10 Or look = 13
		GetChar
	Wend	
EndFunction

Function skipblanks()
	While look = 9 Or look = 32
		GetChar
	Wend
EndFunction

Function endline()
	Return look = 13 Or look = 10
EndFunction

Function newline()
	While look <> 13 And look <> 10
		GetChar
	Wend
	skipwhite
EndFunction

Function GetToken()
	token = ""
	If Not isalpha(look) Then Return
	Repeat
		token :+ Chr look
		GetChar
	Until Not isalnum(look)
EndFunction

Function GetName$()
	Local s$
	If Not isalpha(look) Then Return Null
	Repeat
		s :+ Chr look
		GetChar
	Until Not isalnum(look)
	Return s
EndFunction

Function GetNum:String()
	Local r:String, comma
	If Not isdigit(look) And look <> Asc "." Then Return 0
	If look = Asc "." Then r = "0."; comma = True
	Repeat
		r :+ Chr look
		GetChar
		If look = Asc "." Then
			If comma Then
				error "only one comma allowed"
			Else
				r :+ "."
				GetChar
				comma = True
			EndIf 
		EndIf
	Until Not isdigit(look)
	Return r
EndFunction

Function GetStringlit:String()
	Local s:String
	If look <> Asc "~q" Then error "expected ~q"
	GetChar
	While look <> Asc "~q"
		s :+ Chr look
		GetChar
		If look = Asc "~n" Or look = Asc "~r" Then error "expected ~q"
	Wend
	Return s
EndFunction

